package com.songmy.spider.run.callback.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.songmy.spider.run.callback.CallBackFace;
import com.songmy.spider.run.vo.BackType;
import com.songmy.spider.run.vo.CallBack;

public class FileBack implements CallBackFace {

	Logger log = Logger.getLogger(getClass());
	
	private CallBack callBack = null ;

	private JSONObject o = null ;
	
	public void setValue(JSONObject o, CallBack callBack) {
		if(callBack.getCallBackType() != BackType.FILE){
			throw new RuntimeException("类型错误,非文件back");
		}
		this.callBack  = callBack ;
		this.o  = o ; 
		
	}

	public boolean call() {
//		fileWriter();
		return true;
	}

	
	private String fileName(){
		Date nowTime=new Date(); 
		SimpleDateFormat time=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); 
		Random random = new Random();  
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数  
	  
		return callBack.getCallBackStr()+callBack.getUUID()+time.format(nowTime)+rannum+".json" ;
	}
	
	private void fileWriter() {
		String fileName = fileName();
		File f = new File(fileName);
		if(!f.getParentFile().canWrite()){
			log.error(f.getParentFile()+" 不可读写;权限错误");
			return ; 
		}
		if(!f.exists() ){
			//写文件
	        FileOutputStream fop = null;  
	        try{
		        fop = new FileOutputStream(f);  
		        byte[] contentInBytes = o.toJSONString().getBytes();  
	            fop.write(contentInBytes);  
			} catch (IOException e) {
				log.error(e);
			}finally{
	            try {
	            	fop.flush();
		            fop.close();  
				} catch (IOException e) {
					log.error(e);
				}
			}
			
		}else{
		}
		
	}

	public boolean stop() {
		log.debug("停止");
		return false;
	}

}
